<template>
	<view>
		<u-mask :show="isShowLoading">
		    <view style="display: flex;justify-content: center;align-items: center;height: 100%;">
		        <u-loading mode="flower" size="60" /><text style="color:white;">上传中…</text>
		    </view>
		</u-mask>
		<pageheader :setting="settingdata"></pageheader>
		<view class="boxs">
			<view class="normalline" @click="geiclass()">
				<view class="linetext"><text>*</text>分类名称</view>
				<view class="linevalue" v-if="cate.name">{{cate.name}}</view>
				<text class="jumptext" v-else>请选择分类</text>
			</view>
			<view class="normalline">
				<view class="linetext"><text>*</text>求购名称</view>
				<u-input v-model="title" type="text" :border="false" placeholder="请输入求购名称"
					placeholderStyle="color:#B9B9B9" maxlength="30" :auto-height="false" class="lineputs"
					:clearable="false" />
			</view>
			<view class="normalline">
				<view class="linetext"><text>*</text>求购数量</view>
				<u-input v-model="stock" type="number" :border="false" placeholder="请输入货品数量" maxlength="6"
					placeholderStyle="color:#B9B9B9" :auto-height="false" class="lineputs" :clearable="false" />
				<picker @change="setunit" :value="unitindex" :range="unitnamelist">
					<text class="danwei">{{unitnamelist[unitindex]}}</text>
					<u-icon name="arrow-down" color="#A2A2A2" size="24" class="_arrow"></u-icon>
				</picker>
			</view>
			<view class="normalline" @click="setspec">
				<view class="linetext"><text>*</text>货品规格</view>
				<view class="linevalue" v-if="params">{{params}}</view>
				<text class="jumptext" v-else>请选择货品规格</text>
			</view>
			<view class="normalline">
				<view class="linetext">求购单价</view>
				<u-input v-model="money" type="digit" :border="false" placeholder="不填写，待商家报价" maxlength="6"
					placeholderStyle="color:#B9B9B9" :auto-height="false" class="lineputs" :clearable="false" />
				<text class="danwei">元</text>
			</view>
			<view class="normalline" @click="showsh=true">
				<view class="linetext"><text>*</text>求购地区</view>
				<view class="flex_bet_align lineputs">
					<view class="jumptext" v-if="!city[0]">请选择收货地址</view>
					<view class="clamp1" style="max-width: 400rpx;" v-if="city[0]">{{city[0]}} {{city[1]}}
						{{city[2]}}
					</view>
					<view class="iconfont icon-xwtubiaoku-03"></view>
				</view>
				<!-- <simple-address ref="simpleAddress" :pickerValueDefault="cityPickerValueDefault" @onConfirm="onConfirm"
					themeColor="#007AFF"></simple-address>
				<view @tap="openAddres" class="lineputs">
					<view class="flex_bet_align lineputs">
						<view class="jumptext" v-if="!city[0]">请选择求购地区</view>
						<view class="clamp1" style="max-width: 400rpx;" v-if="city[0]">{{city[0]}} {{city[1]}}
							{{city[2]}}
						</view>
						<view class="iconfont icon-xwtubiaoku-03"></view>
					</view>
				</view> -->
			</view>
			<view class="" v-if="city[0]!=''">
				<u-picker v-model="showsh" @confirm="setcity" :range="city" :default-region="city" mode="region"
					class="lineputs"></u-picker>
			</view>


			<view class="normalline" @click="showdate">
				<view class="linetext"><text>*</text>收货地址</view>
				<view class="flex_bet_align lineputs">
					<view class="jumptext" v-if="!address[0]">请选择收货地址</view>
					<view class="clamp1" style="max-width: 400rpx;" v-if="address[0]">{{address[0]}} {{address[1]}}
						{{address[2]}}
					</view>
					<view class="iconfont icon-xwtubiaoku-03"></view>
				</view>
			</view>
			<view class="" v-if="address[0]!=''">
				<u-picker v-model="show" @confirm="setaddress" :range="address" :default-region="address" mode="region"
					class="lineputs"></u-picker>
			</view>

			<!-- <view class="normalline" @click="setdate=true">
				<view class="linetext">截止时间<text>*</text></view>
				<view class="linevalue" v-if="stoptime.length>0">{{stoptime[0]}}年 {{stoptime[1]}}月 {{stoptime[2]}}日
				</view>
				<text class="jumptext" v-else>请选择截止时间</text>
			</view> -->
			<picker mode="date" :value="startDate" :start="nowtime" @change="bindDateChange">
				<view class="normalline">
					<view class="linetext"><text>*</text>截止时间</view>
					<text class="jumptext" v-if="!setdate">请选择截止时间</text>
					<view class="jumptext" v-else>{{startDate}}</view>
				</view>
			</picker>

			<view class="textarealine">
				<view class="linetext"><text>*</text>备注说明</view>
				<view class="textareabox">
					<textarea v-model="content" placeholder="请备注采购的详细清单，如：XXX株" placeholderStyle="color:#B9B9B9"
						class="textarea_content" maxlength='-1' />
				</view>
			</view>
			<view class="imgboxline">
				<view class="imgboxtitle">
					上传内容<text class="_number">({{images.length}}/9)</text>
				</view>
				<view class="imgboxmetion">说明：此处上传求购样品图</view>
				<view class="photos">
					<view class="photobox">
						<u-upload ref="upload" max-size="12328959" :action="action" width="210" height="210" :auto-upload="false"
							max-count="9" :file-list="echoimages" @on-remove="removeimg" @on-uploaded="uploaded">
						</u-upload>
					</view>
				</view>
			</view>
		</view>
		<view class="submitbox">
			<view class="submitbtn" @click="submit">{{id==0?'确认发布':'确认修改'}}</view>
		</view>

		<!-- 		<u-picker mode="time" v-model="setdate" @confirm="getstoptime" :default-time="defaultTime" start-year="2021"
			end-year="2121"></u-picker> -->
	</view>
</template>

<script>
	import amapFile from "../../static/js/amap-wx.js"
	import App from '@/App.vue';
	var _this, shake;
	export default {
		data() {
			return {
				isShowLoading: false,
				settingdata: {
					name: '发布求购',
					bgColor: '#fff',
					titleColor: '#000000',
					showNav: true,
					showTypes: 0,
					position: "submit"
				},
				// 分类
				cate: {
					name: "",
					id: ""
				},
				// 货物名称
				title: "",
				// 单位
				unit: [],
				unitnamelist: [],
				// 选中的单位
				unitindex: 0,
				// 显示的时候返回的单位中文
				unittext: "",
				// 求购数量
				stock: "",
				// 货品规格
				params: "",
				// 单价
				money: "",
				// 供应地址
				city: ["", "", ""],
				// 收货地址
				address: ["", "", ""],
				// 备注
				content: "",
				// 上传内容
				images: [],
				// 回显的img
				echoimages: [],
				// 图片上传请求路径
				action: "",
				// 截止时间
				stoptime: [],
				// 回显时间
				defaultTime: "",
				// 选择时间
				setdate: false,
				show: false,
				id: 0,
				cityPickerValueDefault: [0, 0, 1],
				nowtime: '', //当前时间
				startDate: '',

				showsh: false,
			}
		},
		onLoad(options) {
			_this = this
			_this.action = _this.$api.getbase() + 'fileupload'
			if (options.id > 0) {
				_this.id = options.id
				_this.settingdata.name = "修改求购"
				_this.getdata()
				_this.setdate = true
			} else {
				_this.getunit()
			}
		},
		onShow() {
			_this.getnow()
			if (uni.getStorageSync("cate")) {
				_this.cate = uni.getStorageSync("cate");
				_this.title = _this.cate.s_name;
				console.log(_this.cate);
				_this.params = "";
				uni.removeStorageSync("cate");
			}
			if (uni.getStorageSync("spec")) {
				_this.params = uni.getStorageSync("spec");
				uni.removeStorageSync("spec");
			}
			_this.getcity()
		},
		methods: {
			showdate(){
				console.log();
				_this.show = true;
				console.log(_this.show);
			},
			// 获取数据
			getdata() {
				_this.$api.get("editdemandinfo", {
					id: _this.id
				}).then(data => {
					_this.cate.id = data.cate_ids
					_this.cate.name = data.cate_name
					_this.title = data.titles
					_this.unittext = data.unit
					_this.stock = data.number
					_this.params = data.spec
					_this.money = data.money
					_this.city = data.city.split(',')
					_this.address = data.address.split(',')
					_this.content = data.content
					_this.images = data.images_path
					// _this.defaultTime = data.stoptime
					// _this.stoptime = data.stoptime.split('-')
					_this.startDate = data.stoptime
					data.images.forEach(item => {
						_this.echoimages.push({
							url: item
						})
					})
					_this.getunit()
				});
			},
			bindDateChange: function(e) {
				_this.startDate = e.target.value
				_this.setdate = true
				console.log(_this.startDate)
			},
			// 选择分类
			geiclass() {
				uni.navigateTo({
					url: "/home/submit/choosecatgory"
				})
			},
			// 获取单位
			getunit() {
				_this.$api.get("checkauth", {})
				_this.$api.get("unit", {}).then(data => {
					let index = 0
					for (var item in data) {
						_this.unit.push({
							key: item,
							name: data[item]
						})
						if (_this.unittext == item) {
							_this.unitindex = index
						}
						_this.unitnamelist.push(data[item])
						index++
					}
				});
			},
			// 设置单位
			setunit(e) {
				_this.unitindex = e.target.value
			},
			// 切换城市
			openAddres() {
				_this.$refs.simpleAddress.open();
			},
			onConfirm(e) {
				_this.city = e.label.split('-');
			},

			// 获取当前位置
			getcity() {
				console.log("mapke:",App.mapkey)
				plus.geolocation.getCurrentPosition(function(p) {
					console.log(p)
					// _this.gaode = p.address.city + '----' + p.coords.latitude + '----' + p.coords.longitude
					_this.$api.get("getmapcity", {
						latitude:p.coords.latitude,
						longitude:p.coords.longitude,
					}).then(data => {
						console.log("地图编码",data);
						
								let address = data.result.addressComponent
								let location =  data.result.location
								_this.lat = location[1]
								_this.lon = location[0]
								_this.city = [address.province, address.city, address.district]
								_this.address = [address.province, address.city, address.district]
						// 		console.log(1111)
					});
				}, function(e) {
					console.log("地图编码",e);
					// _this.cuowu = JSON.stringify(e) + '报错'
				});
				// new amapFile.AMapWX({
				// 	key: App.mapkey
				// }).getRegeo({
				// 	success: function(data) {
				// 		let address = data[0].regeocodeData.addressComponent
				// 		let location = address.streetNumber.location.split(',')
				// 		_this.lat = location[1]
				// 		_this.lon = location[0]
				// 		_this.city = [address.province, address.city, address.district]
				// 		_this.address = [address.province, address.city, address.district]
				// 		console.log(1111)
				// 	},
				// 	fail: function(data) {
				// 		console.log(2222)
				// 	}
				// })
			},

			// 收货地址
			setaddress(e) {
				// console.log(e.province.label,e.city.label,e.area.label)
				// _this.address = e.detail.value
				_this.address = [e.province.label, e.city.label, e.area.label]
				console.log(_this.address)
			},
			// 收货地址
			setcity(e) {
				// console.log(e.province.label,e.city.label,e.area.label)
				// _this.address = e.detail.value
				_this.city = [e.province.label, e.city.label, e.area.label]
				console.log(_this.city)
			},
			//设置求购结束时间
			// getstoptime(e) {
			// 	let date = new Date()
			// 	let y = date.getFullYear()
			// 	let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
			// 	let d = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
			// 	if (parseInt(y + M + d) >= parseInt(e.year + e.month + e.day)) {
			// 		uni.showToast({
			// 			title: "至少大于今天",
			// 			icon: "none"
			// 		})
			// 	} else {
			// 		_this.stoptime = [e.year, e.month, e.day]
			// 		_this.setdate = false
			// 	}
			// },
			// 选择货品规格
			setspec() {
				if (!_this.cate.id) {
					uni.showToast({
						title: "请选择分类",
						icon: "none"
					})
				} else {
					uni.navigateTo({
						url: "/home/submit/choosesku?id=" + _this.cate.id
					})
				}
			},
			// 删除图片
			removeimg(e) {
				_this.images.splice(e, 1)
			},
			// 上传成功
			uploaded(e) {
				_this.images = []
				e.forEach((item, index) => {
					if (item.response) {
						if (item.response.code == 1) {
							_this.images.push(item.response.data.url)

						} else {
							_this.$refs['upload'].remove(index)
						}
					}
				})
			},
			// 提交
			submit() {
				_this.click_shake(function() {
					let data = [{
						value: _this.cate.name,
						type: 1,
						title: "请选择分类"
					}, {
						value: _this.title,
						type: 1,
						title: "请输入货品名称"
					}, {
						value: _this.stock,
						type: 1,
						title: "请输入求购数量"
					}, {
						value: _this.params,
						type: 1,
						title: "请选择货品规格"
					}, {
						value: _this.city[0].length,
						type: 2,
						title: "请选择求购地区"
					}, {
						value: _this.address[0].length,
						type: 2,
						title: "请选择收货地址"
					}, {
						value: _this.startDate.length,
						type: 2,
						title: "请选择截止时间"
					}, {
						value: _this.content,
						type: 1,
						title: "请输入备注"
					}]
					if (_this.$plug.verify(data)) {
						_this.isShowLoading = true
						// 上传图片
						if (_this.$refs?.upload?.lists?.length) {
							_this.uploadImage();
						}
						if (_this.id == 0) {
							_this.$api.post("releasedemand", {
								cate_ids: _this.cate.id,
								titles: _this.title,
								number: _this.stock,
								spec: _this.params,
								money: _this.money,
								city: _this.city.join(','),
								address: _this.address.join(','),
								stoptime: _this.startDate,
								content: _this.content,
								images: _this.images,
								unit: _this.unit[_this.unitindex].key,
								supply_type: 1
							}).then(data => {
								_this.isShowLoading = false
								uni.showToast({
									title: "发布成功"
								})
								setTimeout(function() {
									uni.navigateBack({
										delta: 1
									})
								}, 500);
							});
						} else {
							_this.$api.post("releasedemand", {
								cate_ids: _this.cate.id,
								titles: _this.title,
								number: _this.stock,
								spec: _this.params,
								money: _this.money,
								city: _this.city.join(','),
								address: _this.address.join(','),
								stoptime: _this.startDate,
								content: _this.content ? _this.content : '',
								images: _this.images ? _this.images : '',
								unit: _this.unit[_this.unitindex].key,
								supply_type: 2,
								id: _this.id
							}).then(data => {
								_this.isShowLoading = false
								uni.showToast({
									title: "修改成功"
								})
								setTimeout(function() {
									uni.navigateBack({
										delta: 1
									})
								}, 500);
							});
						}
					}
				})
			},
			// 防抖点击
			click_shake(fn) {
				if (!_this.shake) {
					fn && typeof fn === 'function' && fn()
					_this.shake = true
					setTimeout(function() {
						_this.shake = false
					}, 500)
				}
			},
			// 一次性上传图片
			uploadImage() {
				return new Promise((resolve,reject) => {
					_this.uploaded = (e) => {
						_this.images = _this.images ? _this.images : []
						e.forEach((item, index) => {
							if (item.response) {
								if (item.response.code == 1) {
									_this.images.push(item.response.data.url)
								} else {
									_this.$refs['upload'].remove(index)
								}
							}
						})
						resolve()
					}
					_this.$refs.upload.upload();
				})
			},
			

			getnow() {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate() + 1
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				// day = day + 1
				console.log(day)
				this.nowtime = `${year}-${month}-${day}`

				console.log(`${year}-${month}-${day}`, this.nowtime)
				return `${year}-${month}-${day}`;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.boxs {
		padding: 0 25rpx;
		display: flex;
		flex-direction: column;
		border-top: 10rpx solid #F2F2F2;
		padding-bottom: 170rpx;
		padding-bottom: calc(env(safe-area-inset-bottom) + 170rpx);

		.normalline {
			height: 120rpx;
			padding: 0 0 0 9rpx;
			display: flex;
			flex-direction: row;
			align-items: center;
			border-bottom: 2rpx solid #E6E6E6;

			.linetext {
				color: #222222;
				font-size: 30rpx;
				font-weight: bold;
				width: 200rpx;

				text {
					color: #FF0000;
				}
			}

			.jumptext {
				color: #B9B9B9;
				font-size: 30rpx;
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
				flex: 1;
			}

			.linevalue {
				color: #222222;
				font-size: 30rpx;
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
				flex: 1;
			}

			.lineputs {
				flex: 1;
			}

			.danwei {
				color: #222222;
				font-size: 30rpx;
			}

			._arrow {
				margin-left: 11rpx;
			}
		}

		.textarealine {
			display: flex;
			flex-direction: column;
			padding: 39rpx 0 39rpx 9rpx;
			border-bottom: 2rpx solid #E6E6E6;

			.linetext {
				color: #222222;
				font-size: 30rpx;
				font-weight: bold;

				text {
					color: #FF0000;
				}
			}

			.textareabox {
				padding: 25rpx 29rpx;
				background: #F9F9F9;
				border: 2rpx solid #DADADA;
				border-radius: 10rpx;
				display: flex;
				flex-direction: column;
				margin-top: 40rpx;

				text {
					font-weight: normal;
					color: #999999;
					font-size: 20rpx;
					text-align: right;
					margin-top: 20rpx;
				}
			}
		}

		.imgboxline {
			display: flex;
			flex-direction: column;
			padding-left: 9rpx;

			.imgboxtitle {
				margin-top: 43rpx;
				color: #222222;
				font-size: 30rpx;
				font-weight: bold;

				._xing {
					color: #FF0000;
				}

				._number {
					margin-left: 10rpx;
					color: #999999;
					font-size: 28rpx;
				}
			}

			.imgboxmetion {
				margin-top: 26rpx;
				color: #BEBEBE;
				font-size: 24rpx;
			}

			.photos {
				display: flex;
				flex-direction: column;
				margin-top: 27rpx;

				.photobox {
					margin-top: 10rpx;

					.video {
						width: 100%;
						height: 410rpx;
						border-radius: 5rpx;
					}

					.imgupdata {
						width: 100%;
						height: 410rpx;
						border: 2rpx solid #C1C1C1;
						border-radius: 4rpx;
						text-align: center;

						image {
							width: 66rpx;
							height: auto;
							margin: 150rpx auto 40rpx;
						}

						.text {
							width: 100%;
							text-align: center;
							font-size: 30rpx;
							color: #999999;
						}
					}
				}
			}
		}
	}

	.submitbox {
		padding: 39rpx 0 calc(env(safe-area-inset-bottom) + 39rpx) 0;
		padding: 39rpx 0;
		display: flex;
		align-items: center;
		justify-content: center;
		background: #fff;
		width: 100%;
		position: fixed;
		bottom: 0;
		z-index: 99;

		.submitbtn {
			width: 680rpx;
			height: 90rpx;
			border-radius: 45rpx;
			background: linear-gradient(86deg, #38BE8C, #05ADBB);
			text-align: center;
			line-height: 90rpx;
			color: #fff;
			font-size: 34rpx;
			font-weight: bold;
		}
	}
</style>
